<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="form_box"
      size="large"
      v-bind="$attrs"
    >
      <!-- <el-form-item label="推广平台" prop="name" v-if="!isOperate">
        {{ formData.platform === "tt2" ? "巨量2.0" : "星图" }}
      </el-form-item> -->
      <el-form-item label="推广平台" prop="platform">
        <el-select
          v-model="formData.platform"
          placeholder="请选择"
          @change="getTem(formData.platform)"
        >
          <el-option
            v-for="(item, i) in platformOption"
            :key="i"
            :label="item.label"
            :value="item.value"
            :disabled="item.disabled"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="回传配置"
        prop="useDefault"
        v-if="isDefaultTemp != 'default'"
      >
        <el-select v-model="formData.useDefault" placeholder="请选择">
          <el-option label="使用自定义回传" :value="false" />
          <el-option label="使用默认回传" :value="true" />
        </el-select>
      </el-form-item>
      <template v-if="!formData.useDefault">
        <el-form-item label="激活事件" prop="activeEventOption">
          <el-select
            v-model="formData.activeEventOption"
            placeholder="请选择"
            :disabled="isAuth"
          >
            <el-option
              v-for="(item, index) in option2"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充值事件" prop="rechargeEventEnabled">
          <el-switch
            v-model="formData.rechargeEventEnabled"
            :disabled="isAuth"
          />
        </el-form-item>
        <!-- 充值事件为false不展示 -->
        <div v-if="formData.rechargeEventEnabled">
          <el-form-item
            label="回传周期"
            prop="periodLimit"
            style="margin-left: -18px"
          >
            <el-tooltip
              effect="dark"
              content="用户激活多长时间内"
              placement="top"
            >
              <el-icon
                class="tooltip_color"
                style="margin: 0 10px 0 -10px; font-size: 18px; cursor: pointer"
              >
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            <el-select
              v-model="formData.periodLimit"
              placeholder="请选择"
              class="inputWidth_130"
              style="margin-right: 12px"
              :disabled="isAuth"
            >
              <el-option
                v-for="(item, index) in option3"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-model="formData.periodType"
              placeholder="请选择"
              style="width: 100px"
              @change="handlePeriodType"
              :disabled="isAuth"
            >
              <el-option label="小时" :value="1" />
              <el-option label="天" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="激活后充值次数" prop="rechargeLimitTimes">
            <el-select
              v-model="formData.rechargeLimitTimes"
              placeholder="请选择"
              class="inputWidth_130"
              :disabled="isAuth"
            >
              <el-option
                v-for="(item, index) in option4"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="充值金额"
            prop="rechargeMinAmount"
            class="price_box"
          >
            <el-select
              v-model="formData.rechargeType"
              placeholder="请选择"
              class="inputWidth_130"
              :disabled="isAuth"
              @change="handleRechargeAmount"
            >
              <el-option label="不限制" :value="1" />
              <el-option label="不低于" :value="2" />
            </el-select>
            <template v-if="formData.rechargeType == 2">
              <el-input
                v-model="formData.rechargeMinAmount"
                placeholder=""
                class="inputWidth_130"
                style="margin-left: 12px"
                :disabled="isAuth"
              />
              &nbsp;元
            </template>
          </el-form-item>

          <div style="margin: 26px 0 20px">
            <strong> 扣量 </strong>&nbsp;
            <span class="grey">
              符合以上条件的订单可以按照金额和数量进行扣量回传</span
            >
          </div>
          <el-form-item label="金额" prop="rechargeAmountDiscount">
            <el-select
              v-model="formData.priceType"
              placeholder="请选择"
              class="inputWidth_130"
              style="margin-right: 12px"
              @change="handleAmount"
              :disabled="isAuth"
            >
              <el-option label="全额回传" :value="1" />
              <el-option label="不回传金额" :value="2" />
              <el-option label="按折扣回传" :value="3" />
            </el-select>
            <el-select
              v-if="formData.priceType == 3"
              v-model="formData.rechargeAmountDiscount"
              placeholder="请选择"
              class="inputWidth_130"
              :disabled="isAuth"
            >
              <el-option
                v-for="(item, index) in option5"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="数量"
            prop="proportionFeedbackPercent"
            class="nums_box"
            :class="[formData.scaleType === 2 ? 'show' : 'none']"
            style="margin-left: -18px"
          >
            <el-tooltip
              effect="dark"
              content="该推链当天符合条件的订单数量"
              placement="top"
            >
              <el-icon
                class="tooltip_color"
                style="margin: 0 10px 0 -10px; font-size: 18px; cursor: pointer"
              >
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            <el-select
              v-model="formData.scaleType"
              placeholder="请选择"
              class="inputWidth_130"
              :disabled="isAuth"
              @change="handleNums"
            >
              <el-option
                v-for="(item, index) in option1"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <template v-if="formData.scaleType === 3">
              &nbsp;&nbsp; 每天先传&nbsp;
              <el-input
                v-model.number="formData.intervalMakeTimes"
                class="inputWidth_50"
                :disabled="isAuth"
              />
              &nbsp;个， 然后每传&nbsp;
              <el-input
                v-model.number="formData.intervalFeedbackTimes"
                class="inputWidth_50"
                :disabled="isAuth"
              />
              &nbsp;个， 跳过&nbsp;
              <el-input
                v-model.number="formData.intervalSkipTimes"
                class="inputWidth_50"
                :disabled="isAuth"
              />
              &nbsp;个
            </template>
            <template v-if="formData.scaleType === 2">
              <el-input
                v-model.number="formData.proportionFeedbackPercent"
                placeholder="请输入0-100整数"
                :min="1"
                :max="100"
                class="inputWidth_130"
                style="margin-left: 12px"
                :disabled="isAuth"
              />
              &nbsp;%
            </template>
          </el-form-item>
        </div>
        <el-form-item v-if="isDefaultTemp == 'default'">
          <el-button
            type="primary"
            @click="confirmDialog(ruleFormRef)"
            style="width: 120px; margin-top: 20px"
            v-if="!isAuth"
          >
            保 存
          </el-button>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, toRefs } from "vue";
import type { FormInstance } from "element-plus";
import { QuestionFilled } from "@element-plus/icons-vue";
import { getAds, setAds } from "@/api/promotionLink/index";
import { getFeedback, updateFeedback } from "@/api/operateCenter/global/index";
import { getAdsFeedback, setAdsFeedback } from "@/api/returnTemp/index";
import { useUserStore } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { auth } from "@/utils/index";
import { cloneDeep } from "lodash-es";

const user = useUserStore().user;
const { isOperate } = useUserStore().user; // 获取是否为运营人员
const { userAppid } = useUserStore().user; // 获取登录appid
console.log("user------", user);

const props = defineProps({
  //  isDefaultTemp 是否等于 default，如果是则为默认回传模板，不是则为推广链接回传模板
  isDefaultTemp: {
    type: String,
    default: "default",
  },
  id: {
    type: Number,
    default: undefined,
  },
  size: {
    type: String || undefined,
    default: "default",
  },
});

const { isDefaultTemp, id } = toRefs(props);
console.log(id?.value, "id ---------");

const ruleFormRef = ref<FormInstance>();
const form = {
  id: id?.value || undefined,
  useDefault: false,
  platform: "tt2", // 推广平台
  activeEventOption: 1, // 激活事件  1 : 全部回传  2： 首次激活传  3： 不回传
  rechargeEventEnabled: true, // 充值事件
  periodType: 2, // 回传周期类型 1 - 小时, 2 - 天
  periodLimit: 1, // 回传周期值
  rechargeLimitTimes: 1, //激活后充值次数
  rechargeType: 1,
  rechargeMinAmount: 0, // 最小充值金额
  priceType: 1,
  rechargeAmountDiscount: 10, //扣量金额回传比例
  scaleType: 1, // 扣量回传数量类型 1 - 全部回传, 2 - 比例回传, 3 - 间隔回传
  proportionFeedbackPercent: 100, // 扣量数量回传比例
  intervalMakeTimes: 0, // 间隔回传每天先传递的次数
  intervalFeedbackTimes: 0, // 间隔回传次数
  intervalSkipTimes: 0, // 间隔回传跳过次数
};
const formData = ref(Object.assign({}, form));
const platformOption = ref([
  { label: "巨量2", value: "tt2" },
  {
    label: "星图",
    value: "xt",
    disabled: user.userAppObj?.appType === "wx" || id?.value ? true : false,
  },
]);

const option1 = [
  { label: "全部回传", value: 1 },
  { label: "比例回传", value: 2 },
  { label: "间隔回传", value: 3 },
];
const option2 = [
  { label: "全部回传", value: 1 },
  { label: "只回传首次激活", value: 2 },
  { label: "不回传", value: 3 },
];
const option3 = ref([
  { label: "1", value: 1 },
  { label: "2", value: 2 },
  { label: "3", value: 3 },
  { label: "5", value: 5 },
  { label: "7", value: 7 },
  { label: "30", value: 30 },
]);
const option4 = [
  { label: "不限制", value: 0 },
  { label: "1次", value: 1 },
  { label: "2次", value: 2 },
  { label: "3次", value: 3 },
  { label: "4次", value: 4 },
  { label: "5次", value: 5 },
];
const option5 = [
  { label: "1折", value: 1 },
  { label: "2折", value: 2 },
  { label: "5折", value: 5 },
  { label: "7折", value: 7 },
  { label: "8折", value: 8 },
  { label: "9折", value: 9 },
];

// 按钮权限
const isAuth = computed(() => {
  if (isDefaultTemp.value == "default") {
    let api = isOperate
      ? "api:operate:global:saveTemp"
      : "api:agent:global:saveTemp";
    return !auth(api);
  } else {
    return false;
  }
});

// 监听充值事件
watch(
  () => formData.value.rechargeEventEnabled,
  (val: boolean) => {
    if (val) {
      // 当充值事件为true时，给予默认值
      formData.value.periodType = 2;
      formData.value.periodLimit = 1;
      formData.value.rechargeLimitTimes = 1;
      formData.value.rechargeType = 1;
      formData.value.rechargeMinAmount = 0;
      formData.value.priceType = 1;
      formData.value.rechargeAmountDiscount = 8;
      formData.value.scaleType = 1;
      formData.value.proportionFeedbackPercent = 100;
    }
  }
);

watch(
  () => formData.value.rechargeType, // 1： 不限制  2：不低于
  (val: number) => {
    if (val == 1) {
      rules.rechargeMinAmount[0].required = false; // rules 为false非必填
    } else if (val == 2) {
      rules.rechargeMinAmount[0].required = true;
    }
  }
);

watch(
  () => formData.value.scaleType, // 类型 1 - 全部回传, 2 - 比例回传, 3 - 间隔回传
  (val: number) => {
    if (val === 1) {
      rules.proportionFeedbackPercent[0].required = false;
    } else if (val === 2) {
      rules.proportionFeedbackPercent[0].required = true;
    } else if (val === 3) {
      rules.proportionFeedbackPercent[0].required = true;
    }
  }
);

// 充值金额规则
const validataAmount = (rule: any, value: any, callback: any) => {
  let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/; // 最多保留2位小数
  if (formData.value.rechargeType == 2) {
    if (!+value || +value < 0) {
      return callback(new Error("请输入大于0的数字"));
    } else if (!reg.test(value)) {
      return callback(new Error("金额最多保留两位小数"));
    } else if (+value > 9999.99) {
      return callback(new Error(`充值金额最大支持 9999.99 元`));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
// 扣量 - 数量规则
const validataNums = (rule: any, value: any, callback: any) => {
  if (formData.value.scaleType === 2) {
    let reg = /^[1-9]\d*$/; // 大于0的整数
    if (!+value || +value < 0) {
      return callback(new Error("请输入大于1-100之间的整数"));
    } else if (!reg.test(value) || +value >= 100) {
      return callback(new Error("请输入大于1-100之间的整数"));
    } else {
      callback();
    }
  } else if (formData.value.scaleType === 3) {
    let reg = /^[0-9]\d*$/; // 大于等于0的整数
    if (
      !reg.test(formData.value?.intervalMakeTimes.toString()) ||
      !reg.test(formData.value?.intervalFeedbackTimes.toString()) ||
      !reg.test(formData.value?.intervalSkipTimes.toString())
    ) {
      return callback(new Error("间隔回传的数据，需都为0-100之间的整数"));
    } else if (
      formData.value.intervalMakeTimes > 99 ||
      formData.value.intervalFeedbackTimes > 99 ||
      formData.value.intervalSkipTimes > 99
    ) {
      return callback(new Error("间隔回传的数据不能超过99"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};

const rules = reactive({
  activeEventOption: [
    { required: true, message: "请选择回传周期", trigger: "change" },
  ],
  rechargeEventEnabled: [
    { required: true, message: "请选择事件", trigger: "change" },
  ],
  periodLimit: [
    { required: true, message: "请选择回传周期", trigger: "change" },
  ],
  rechargeLimitTimes: [
    { required: true, message: "请选择充值次数", trigger: "change" },
  ],
  rechargeMinAmount: [
    { required: false, validator: validataAmount, trigger: "change" },
  ],
  rechargeAmountDiscount: [
    { required: true, message: "请选择金额", trigger: "change" },
  ],
  proportionFeedbackPercent: [
    { required: false, validator: validataNums, trigger: "change" },
  ],
});

// 切换回传周期
const handlePeriodType = (val: number) => {
  if (val === 1) {
    formData.value.periodLimit = 24;
  } else {
    formData.value.periodLimit = 1;
  }
};

// 切换充值金额
const handleRechargeAmount = (val: number) => {
  if (val == 1) {
    formData.value.rechargeMinAmount = 0;
  } else if (val == 2) {
    formData.value.rechargeMinAmount = 10;
  }
};

// 切换金额
const handleAmount = (val: number) => {
  if (val === 3) formData.value.rechargeAmountDiscount = 8;
};

// 切换扣量数量
const handleNums = (val: number) => {
  if (val === 1) {
    formData.value.proportionFeedbackPercent = 100;
    formData.value.intervalMakeTimes = 0;
    formData.value.intervalFeedbackTimes = 0;
    formData.value.intervalSkipTimes = 0;
  } else if (val === 2) {
    formData.value.proportionFeedbackPercent = 80;
    formData.value.intervalMakeTimes = 0;
    formData.value.intervalFeedbackTimes = 0;
    formData.value.intervalSkipTimes = 0;
  } else if (val === 3) {
    formData.value.proportionFeedbackPercent = 0;
    formData.value.intervalMakeTimes = 1;
    formData.value.intervalFeedbackTimes = 1;
    formData.value.intervalSkipTimes = 1;
  }
};

// 成功
const confirmDialog = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  return await formEl.validate((valid) => {
    if (valid) {
      let tempD: any = formData.value;
      tempD.rechargeAmountDiscount =
        tempD.priceType == 1
          ? 10
          : tempD.priceType == 2
          ? 0
          : tempD.rechargeAmountDiscount;
      tempD.rechargeMinAmount =
        tempD.rechargeType == 1 ? 0 : tempD.rechargeMinAmount;

      let URL;
      // isDefaultTemp 为default时 默认回传模板生效
      let isDef = isDefaultTemp.value === "default";
      if (isDef) {
        URL = isOperate ? updateFeedback : setAdsFeedback;
        if (!isOperate) {
          tempD.appId = +userAppid;
        }
      } else {
        URL = setAds;
        tempD.id = props.id;
      }
      URL(tempD).then(() => {
        ElMessage.success(`${isDef ? "保存" : "设置"}成功`);
      });
    }
    return valid;
  });
};

// 获取回传设置信息
const getTem = (val: any = null) => {
  console.log("val ---------", val);

  let URL, params: any;
  // 判断 isDefaultTemp 是否等于 default，如果是则为默认回传模板，不是则为推广链接回传模板
  if (isDefaultTemp.value == "default") {
    URL = isOperate ? getFeedback : getAdsFeedback;
    params = {
      platform: val || "tt2",
    };
    if (!isOperate) {
      params.appId = +userAppid; // appid
    }
  } else {
    URL = getAds;
    params = id?.value;
  }
  URL(params).then((res: any) => {
    if (!res) return;
    if (res) {
      let data;
      //  运营平台/分销商 回传模板都为object对象
      data = res;

      // let data = isOperate ? res[0] : res;
      formData.value = cloneDeep(data);
      formData.value.rechargeType = formData.value?.rechargeMinAmount ? 2 : 1;
      formData.value.activeEventOption = formData.value?.activeEventOption || 1;
      formData.value.priceType = !formData.value?.rechargeAmountDiscount
        ? 2
        : formData.value?.rechargeAmountDiscount == 10
        ? 1
        : 3;
    } else {
      formData.value.rechargeEventEnabled = false;
      formData.value.activeEventOption = 1;
    }
  });
};

watch(
  () => formData.value.periodType,
  (val: number) => {
    if (val === 1) {
      option3.value = [
        { label: "12", value: 12 },
        { label: "24", value: 24 },
        { label: "48", value: 48 },
        { label: "72", value: 72 },
      ];
    } else {
      option3.value = [
        { label: "1", value: 1 },
        { label: "2", value: 2 },
        { label: "3", value: 3 },
        { label: "5", value: 5 },
        { label: "7", value: 7 },
        { label: "30", value: 30 },
      ];
    }
  },
  { immediate: true }
);

onMounted(() => {
  getTem();
});

defineExpose({
  confirmDialog,
  ruleFormRef,
});
</script>
<style scoped lang="scss">
.price_box {
  :deep(.el-form-item__error) {
    padding-left: 141px;
  }
}

.nums_box {
  :deep(.el-form-item__error) {
    padding-left: 159px;
  }
}

.inputWidth_130 {
  width: 130px;
}

.inputWidth_50 {
  width: 60px;
}
</style>
